#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_AVAILABLE_PATH/docker-options/functions"
source "$PLUGIN_AVAILABLE_PATH/ps/functions"

cmd-ps-set-restart-policy() {
  declare desc="sets app restart-policy"
  declare cmd="ps:set-restart-policy"
  [[ "$1" == "$cmd" ]] && shift 1
  declare APP="$1" RESTART_POLICY="$2"

  [[ -z "$APP" ]] && dokku_log_fail "Please specify an app to run the command on"
  verify_app_name "$APP"
  local RE_RESTART_POLICY="^(no|unless-stopped|always|on-failure(:[1-9][0-9]*)?)$"

  if [[ ! "$RESTART_POLICY" =~ $RE_RESTART_POLICY ]]; then
    dokku_log_fail "Please specify an valid restart policy matching the following regex: ${RE_RESTART_POLICY}"
  fi

  local RESTART_POLICIES=$(get_raw_restart_policies "$(get_phase_file_path "deploy")")
  local passed_phases=(deploy)

  for policy in $RESTART_POLICIES; do
    remove_passed_docker_option passed_phases[@] "$policy"
  done

  dokku_log_info1_quiet "Setting restart policy: ${RESTART_POLICY}"
  local passed_phases=(deploy)
  add_passed_docker_option passed_phases[@] "--restart=${RESTART_POLICY}"
}

cmd-ps-set-restart-policy "$@"
